import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'
import router from '@/router'
import api from '@/services/api'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref(localStorage.getItem('access_token'))
  const refreshToken = ref(localStorage.getItem('refresh_token'))
  const user = ref(JSON.parse(localStorage.getItem('user_info') || 'null'))
  const loading = ref(false)

  // 计算属性
  const isAuthenticated = computed(() => !!token.value)
  const userInfo = computed(() => user.value)

  // 登录
  const login = async (credentials) => {
    loading.value = true
    try {
      const response = await api.post('/user/login', credentials)
      
      if (response.data.code === 200) {
        const { access_token, refresh_token, user_info } = response.data.data
        
        // 保存到本地存储
        token.value = access_token
        refreshToken.value = refresh_token
        user.value = user_info
        
        localStorage.setItem('access_token', access_token)
        localStorage.setItem('refresh_token', refresh_token)
        localStorage.setItem('user_info', JSON.stringify(user_info))
        
        return { success: true, data: response.data.data }
      } else {
        return { success: false, message: response.data.message }
      }
    } catch (error) {
      return { 
        success: false, 
        message: error.response?.data?.message || '登录失败' 
      }
    } finally {
      loading.value = false
    }
  }

  // 退出登录
  const logout = async () => {
    loading.value = true
    try {
      if (token.value) {
        await api.post('/user/logout', {
          access_token: token.value
        })
      }
    } catch (error) {
      console.error('退出登录请求失败:', error)
    } finally {
      // 清除本地存储
      token.value = null
      refreshToken.value = null
      user.value = null
      
      localStorage.removeItem('access_token')
      localStorage.removeItem('refresh_token')
      localStorage.removeItem('user_info')
      
      loading.value = false
      
      // 跳转到登录页
      router.push('/login')
    }
  }

  return {
    // 状态
    token,
    refreshToken,
    user,
    loading,
    
    // 计算属性
    isAuthenticated,
    userInfo,
    
    // 方法
    login,
    logout
  }
})